package rta.datos
{
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.errors.SQLError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.states.State;

	public class DB
	{
		private static var dbFile:File;
		public static var connection:SQLConnection;
		public static var callback:Function;
		
		public static function conectar():void{
			var dirDB:File = obtenerDirectorioDB();
			
			dbFile = dirDB.resolvePath("rta.db");
			
			if(dbFile.exists){ 
				continuarConexion();
			}else{
				var source:File = File.applicationDirectory.resolvePath("rta.db");				
				source.copyTo(dbFile, true);
				
				continuarConexion();
			}			
		}
		
		private static function continuarConexion():void{
			connection = new SQLConnection();
			connection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
			connection.addEventListener(SQLErrorEvent.ERROR, errorHandler);
			connection.open(dbFile);	
		}
		
		private static function onDatabaseOpen(event:SQLEvent):void
		{
			if(DB.callback != null)
				callback();
		}
		
		private static function errorHandler(error:SQLError):void
		{
			Alert("Error Occurred with id: " + error.errorID  + " operation " + error.operation + " message " + error.message);
		}

		private static function obtenerDirectorioDB():File{
			var dir:File = File.applicationStorageDirectory.resolvePath("data/db/1.1.1");
			if(!dir.exists)
				dir.createDirectory();
			
			return dir;
		}
	}
}